package com.sk.weichat.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.message.MucChatActivity;
import com.sk.weichat.ui.message.search.SearchDesignationContent;
import com.sk.weichat.ui.mucfile.DownManager;
import com.sk.weichat.ui.mucfile.MucFileDetails;
import com.sk.weichat.ui.mucfile.XfileUtils;
import com.sk.weichat.ui.mucfile.bean.MucFileBean;
import com.sk.weichat.ui.tool.WebViewActivity;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.view.CircleImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.sk.weichat.ui.tool.WebViewActivity.EXTRA_URL;

public class DesignationContentAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<ChatMessage> mChatMessageSource;

    private Context mContext;
    private String mSearchObject;

    public DesignationContentAdapter(Context mContext,List<ChatMessage> chatMessages,String mSearchObject) {
        this.mChatMessageSource = chatMessages;
        if (mChatMessageSource == null) {
            mChatMessageSource = new ArrayList<>();
        }
        this.mContext = mContext;
        this.mSearchObject = mSearchObject;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new DesignationContentHolder(LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_designation, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {

        DesignationContentHolder holder = (DesignationContentHolder) viewHolder;
        ChatMessage chatMessage = mChatMessageSource.get(i);
        Friend friend = FriendDao.getInstance().getFriend(CoreManager.getSelf(mContext).getUserId(), chatMessage.getFromUserId());
        String name = chatMessage.getFromUserName();
        if (friend != null && !TextUtils.isEmpty(friend.getRemarkName())) {
            name = friend.getRemarkName();
        }
        AvatarHelper.getInstance().displayAvatar(name, chatMessage.getFromUserId(),
                holder.mAvatarIv, true);
        if (chatMessage.getType() == XmppMessage.TYPE_TRANSFER) {
            holder.mNameTv.setText(mContext.getString(R.string.start_transfer, name));
        } else {
            holder.mNameTv.setText(name);
        }
        holder.mDateTv.setText(TimeUtils.getFriendlyTimeDesc(mContext,
                chatMessage.getTimeSend()));
        if (chatMessage.getType() == XmppMessage.TYPE_FILE) {
            // 文件
            fillFileData(chatMessage, holder.mAbstractLl, holder.mAbstractLeftIv,
                    holder.mAbstractTopTv, holder.mAbstractBottomTv);
        } else if (chatMessage.getType() == XmppMessage.TYPE_LINK || chatMessage.getType() == XmppMessage.TYPE_SHARE_LINK) {
            // 链接
            holder.mAbstractBottomTv.setVisibility(View.GONE);
            fillLinkData(chatMessage, holder.mAbstractLl, holder.mAbstractLeftIv,
                    holder.mAbstractTopTv, holder.mAbstractBottomTv);
        } else if (chatMessage.getType() == XmppMessage.TYPE_RED || chatMessage.getType() == XmppMessage.TYPE_TRANSFER) {
            // 红包与转账
            fillRedTransferData(chatMessage,holder.mAbstractLl, holder.mAbstractLeftIv,holder.mAbstractTopTv, holder.mAbstractBottomTv);
        }
    }

    @Override
    public int getItemCount() {
        return mChatMessageSource.size();
    }

    private void fillFileData(ChatMessage chatMessage, RelativeLayout ll, ImageView iv, TextView topTv, TextView bottomTv) {
        String filePath = TextUtils.isEmpty(chatMessage.getFilePath()) ? chatMessage.getContent() : chatMessage.getFilePath();
        int index = filePath.lastIndexOf(".");
        String type = filePath.substring(index + 1).toLowerCase();
        int start = filePath.lastIndexOf("/");
        String fileName = filePath.substring(start + 1).toLowerCase();

        if (type.equals("png") || type.equals("jpg")) {
            Glide.with(mContext)
                    .load(filePath)
                    .error(R.drawable.image_download_fail_icon)
                    .into(iv);
        } else {
            AvatarHelper.getInstance().fillFileView(type, iv);
        }
        topTv.setSingleLine();
        topTv.setText(fileName);
        bottomTv.setText(XfileUtils.fromatSize(chatMessage.getFileSize()));

        ll.setOnClickListener(v -> {
            MucFileBean mucFileBean = new MucFileBean();
            mucFileBean.setName(fileName);
            mucFileBean.setNickname(fileName);
            mucFileBean.setUrl(chatMessage.getContent());
            mucFileBean.setSize(chatMessage.getFileSize());
            mucFileBean.setState(DownManager.STATE_UNDOWNLOAD);
            mucFileBean.setType(XfileUtils.getFileType(type));
            Intent intent = new Intent(mContext, MucFileDetails.class);
            intent.putExtra("data", mucFileBean);
            mContext.startActivity(intent);
        });
    }

    private void fillLinkData(ChatMessage chatMessage, RelativeLayout ll, ImageView iv, TextView topTv, TextView bottomTv) {
        if (chatMessage.getType() == XmppMessage.TYPE_LINK) {
            ll.setBackground(mContext.getResources().getDrawable(R.color.white));
            topTv.setMaxLines(2);
            // 普通链接
            try {
                JSONObject json = new JSONObject(chatMessage.getContent());
                String linkTitle = json.getString("title");
                String linkImage = json.getString("img");
                String linkAddress = json.getString("url");

                Glide.with(mContext)
                        .load(linkImage)
                        .error( R.mipmap.img_link)
                        .into(iv);
                topTv.setText(linkTitle);

                ll.setOnClickListener(v -> {
                    Intent intent = new Intent(mContext, WebViewActivity.class);
                    intent.putExtra("toUserId", chatMessage.getToUserId());
                    intent.putExtra(EXTRA_URL, linkAddress);
                    mContext.startActivity(intent);
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // SK ShareSDK 分享进来的链接
            try {
                JSONObject json = new JSONObject(chatMessage.getObjectId());
                String appName = json.getString("appName");
                String appIcon = json.getString("appIcon");
                String title = json.getString("title");
                String subTitle = json.getString("subTitle");
                String imageUrl = json.getString("imageUrl");
                String linkShareAddress = json.getString("url");
                String linkShareDownAppAddress = json.getString("downloadUrl");

                if (TextUtils.isEmpty(appIcon) && TextUtils.isEmpty(imageUrl)) {
                    iv.setImageResource(R.mipmap.img_link);
                } else if (TextUtils.isEmpty(imageUrl)) {
                    AvatarHelper.getInstance().displayUrl(appIcon, iv);
                } else {
                    AvatarHelper.getInstance().displayUrl(imageUrl, iv);
                }
                topTv.setText(title);
                bottomTv.setText(subTitle);

                ll.setOnClickListener(v -> {
                    Intent intent = new Intent(mContext, WebViewActivity.class);
                    intent.putExtra(WebViewActivity.EXTRA_URL, linkShareAddress);
                    intent.putExtra("toUserId", chatMessage.getToUserId());
                    intent.putExtra(WebViewActivity.EXTRA_DOWNLOAD_URL, linkShareDownAppAddress);
                    mContext.startActivity(intent);
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void fillRedTransferData(ChatMessage chatMessage, RelativeLayout ll, ImageView iv, TextView topTv, TextView bottomTv) {
        if (chatMessage.getType() == XmppMessage.TYPE_RED) {
            // 红包
            iv.setImageResource(R.drawable.ic_chat_hongbao);
            topTv.setText(chatMessage.getContent());
        } else {
            // 转账
            iv.setImageResource(R.drawable.ic_tip_transfer_money);
            topTv.setText("￥ " + chatMessage.getContent());
            bottomTv.setText(chatMessage.getFilePath());
        }

        ll.setOnClickListener(v -> {
            Friend friend = FriendDao.getInstance().getFriend(CoreManager.getSelf(mContext).getUserId(), mSearchObject);
            if (friend != null) {
                Intent intent = new Intent();
                if (friend.getRoomFlag() == 0) { // 个人
                    intent.setClass(mContext, ChatActivity.class);
                    intent.putExtra(ChatActivity.FRIEND, friend);
                } else {
                    intent.setClass(mContext, MucChatActivity.class);
                    intent.putExtra(AppConstant.EXTRA_USER_ID, friend.getUserId());
                    intent.putExtra(AppConstant.EXTRA_NICK_NAME, friend.getNickName());
                }

                intent.putExtra("isserch", true);
                intent.putExtra("jilu_id", chatMessage.getDoubleTimeSend());
                mContext.startActivity(intent);
            }
        });
    }

    class DesignationContentHolder extends RecyclerView.ViewHolder {

        private CircleImageView mAvatarIv;
        private TextView mNameTv, mDateTv;

        private RelativeLayout mAbstractLl;
        private ImageView mAbstractLeftIv;
        private TextView mAbstractTopTv, mAbstractBottomTv;

        public DesignationContentHolder(@NonNull View itemView) {
            super(itemView);
            mAvatarIv = itemView.findViewById(R.id.avatar_iv);
            mNameTv = itemView.findViewById(R.id.name_tv);
            mDateTv = itemView.findViewById(R.id.date_tv);
            mAbstractLl = itemView.findViewById(R.id.abstract_ll);
            mAbstractLeftIv = itemView.findViewById(R.id.abstract_left_iv);
            mAbstractTopTv = itemView.findViewById(R.id.abstract_top_tv);
            mAbstractBottomTv = itemView.findViewById(R.id.abstract_bottom_tv);
        }
    }
}

